package com.wsoft.excel.listener;

import cn.hutool.core.util.ObjUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.wsoft.annotation.ExcelFieldConvert;
import com.wsoft.excel.converter.FieldDictConvert;
import com.wsoft.excel.converter.GenericConverter;
import kotlin.Triple;
import lombok.Getter;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Excel 导入 通用读取监听器
 * @Author z001
 * @Date 2024/11/7 08:52
 */
public class GenericAnalysisEventListener<T> extends AnalysisEventListener<T> {

    @Getter
    private final List<T> dataList = new ArrayList<>();
    private final Class<T> clazz;
    private final Map<Triple<String, String, String>, Object> dataMap;

    public GenericAnalysisEventListener(Class<T> clazz, Map<Triple<String, String, String>, Object> dataMap) {
        this.clazz = clazz;
        this.dataMap = dataMap;
    }

    @Override
    public void invoke(T data, AnalysisContext context) {
        try {
            for (Field field : clazz.getDeclaredFields()) {
                field.setAccessible(true);
                Object value = field.get(data);
                //转换字典
                if (field.isAnnotationPresent(ExcelFieldConvert.class)) {
                    if(ObjUtil.isNotEmpty(value)){
                        ExcelFieldConvert excelFieldConvert = field.getAnnotation(ExcelFieldConvert.class);
                        String type = excelFieldConvert.type();
                        String dictCode = excelFieldConvert.dictCode();
                        FieldDictConvert fieldDictConvert = new FieldDictConvert(dataMap);
                        value = fieldDictConvert.getResult(type, dictCode, value.toString());
                    }
                } else {
                    ReadCellData cellData = new ReadCellData(value);
                    ExcelContentProperty contentProperty = new ExcelContentProperty();
                    contentProperty.setField(field);
                    //其他格式转换
                    value = new GenericConverter().convertToJavaData(cellData, contentProperty, null);
                }
                field.set(data, value);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        dataList.add(data);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 所有数据解析完成后的操作
    }

}